<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="资源名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="资源类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择资源类型" clearable>
            <el-option
              v-for="dict in mediaTypeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上传日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          type="success"
          icon="plus"
          @click="handleOpenUploadDialog()"
        >
          上传资源
        </el-button>
      </div>

      <div v-if="viewMode === 'grid'" class="media-grid">
        <el-empty v-if="mediaList.length === 0" description="暂无数据" />
        <div v-else class="media-container">
          <el-card
            v-for="item in mediaList"
            :key="item.id"
            :body-style="{ padding: '0px' }"
            class="media-item"
            shadow="hover"
            @click="handleMediaClick(item)"
          >
            <div class="media-preview">
              <img v-if="item.type === 1" :src="item.url" alt="照片预览" class="media-image" />
              <video v-else-if="item.type === 2" :src="item.url" class="media-image" />
              <div v-else class="media-file-icon">
                <el-icon size="40"><Document /></el-icon>
              </div>
            </div>
            <div class="media-info">
              <div class="media-title">{{ item.name }}</div>
              <div class="media-meta">
                <el-tag size="small" :type="getMediaTypeTag(item.type)">
                  {{ getMediaTypeName(item.type) }}
                </el-tag>
                <span class="media-size">{{ formatFileSize(item.size) }}</span>
              </div>
              <div class="media-actions">
                <el-button
                  type="primary"
                  link
                  size="small"
                  icon="view"
                  @click.stop="handlePreview(item)"
                >
                  预览
                </el-button>
                <el-button
                  type="primary"
                  link
                  size="small"
                  icon="download"
                  @click.stop="handleDownload(item)"
                >
                  下载
                </el-button>
                <el-button
                  type="danger"
                  link
                  size="small"
                  icon="delete"
                  @click.stop="handleDelete(item.id)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>

      <el-table
        v-else
        v-loading="loading"
        :data="mediaList"
        highlight-current-row
        @row-click="handleMediaClick"
      >
        <el-table-column label="预览" width="100" align="center">
          <template #default="scope">
            <el-image 
              v-if="scope.row.type === 1"
              :src="scope.row.url" 
              :preview-src-list="[scope.row.url]"
              fit="cover"
              style="width: 50px; height: 50px"
            />
            <el-icon v-else-if="scope.row.type === 2" size="24"><VideoCamera /></el-icon>
            <el-icon v-else size="24"><Document /></el-icon>
          </template>
        </el-table-column>
        <el-table-column label="资源名称" prop="name" min-width="180" />
        <el-table-column label="资源类型" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getMediaTypeTag(scope.row.type)">
              {{ getMediaTypeName(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="文件大小" align="center" width="100">
          <template #default="scope">
            {{ formatFileSize(scope.row.size) }}
          </template>
        </el-table-column>
        <el-table-column label="上传时间" prop="createTime" min-width="160" />
        <el-table-column label="关联人物" prop="personName" min-width="120" />
        <el-table-column label="描述" prop="description" min-width="200" show-overflow-tooltip />
        <el-table-column fixed="right" align="center" label="操作" width="180">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              icon="view"
              @click.stop="handlePreview(scope.row)"
            >
              预览
            </el-button>
            <el-button
              type="primary"
              link
              size="small"
              icon="download"
              @click.stop="handleDownload(scope.row)"
            >
              下载
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              icon="delete"
              @click.stop="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="media-toolbar">
        <div class="view-toggle">
          <el-radio-group v-model="viewMode" size="small">
            <el-radio-button label="grid">
              <el-icon><Grid /></el-icon>
            </el-radio-button>
            <el-radio-button label="table">
              <el-icon><List /></el-icon>
            </el-radio-button>
          </el-radio-group>
        </div>
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[12, 24, 36, 48]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 上传资源对话框 -->
    <el-dialog
      v-model="uploadDialog.visible"
      title="上传资源"
      width="500px"
      @close="handleCloseUploadDialog"
    >
      <el-form ref="uploadFormRef" :model="uploadForm" :rules="uploadRules" label-width="80px">
        <el-form-item label="资源文件" prop="file">
          <el-upload
            ref="uploadRef"
            action="#"
            :auto-upload="false"
            :limit="1"
            :on-change="handleFileChange"
            :on-exceed="handleExceed"
            :file-list="fileList"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持图片、视频、文档等格式，大小不超过100MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="资源名称" prop="name">
          <el-input v-model="uploadForm.name" placeholder="请输入资源名称" />
        </el-form-item>

        <el-form-item label="关联人物" prop="personId">
          <el-select
            v-model="uploadForm.personId"
            placeholder="请选择关联人物"
            filterable
            clearable
            @change="handlePersonChange"
          >
            <el-option
              v-for="item in personOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="描述">
          <el-input
            v-model="uploadForm.description"
            type="textarea"
            placeholder="请输入资源描述"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleUploadSubmit">上 传</el-button>
          <el-button @click="handleCloseUploadDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewDialog.visible"
      :title="previewDialog.title"
      width="800px"
      @close="previewDialog.visible = false"
    >
      <div class="preview-container">
        <img 
          v-if="previewDialog.type === 1" 
          :src="previewDialog.url" 
          class="preview-image" 
        />
        <video 
          v-else-if="previewDialog.type === 2" 
          :src="previewDialog.url" 
          controls 
          class="preview-video"
        />
        <div v-else class="preview-file">
          <el-icon size="80"><Document /></el-icon>
          <div class="preview-file-name">{{ previewDialog.name }}</div>
          <el-button type="primary" @click="handleDownload(previewDialog)">下载文件</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { useAppStore } from "@/store/modules/app.store";
import { DeviceEnum } from "@/enums/settings/device.enum";
import { Grid, List, Document, VideoCamera } from '@element-plus/icons-vue';

defineOptions({
  name: "Media",
  inheritAttrs: false,
});

const appStore = useAppStore();

const queryFormRef = ref();
const uploadFormRef = ref();
const uploadRef = ref();

const loading = ref(false);
const viewMode = ref('grid'); // 'grid' 或 'table'

// 资源类型选项
const mediaTypeOptions = ref([
  { value: 1, label: "图片" },
  { value: 2, label: "视频" },
  { value: 3, label: "文档" },
  { value: 4, label: "音频" },
  { value: 5, label: "其他" }
]);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 12,
  keywords: "",
  type: undefined,
});

// 日期范围
const dateRange = ref([]);

// 分页总数
const total = ref(0);

// 资源列表数据
const mediaList = ref([]);

// 人物选项
const personOptions = ref([]);

// 上传对话框
const uploadDialog = reactive({
  visible: false
});

// 预览对话框
const previewDialog = reactive({
  visible: false,
  title: '',
  url: '',
  type: 1,
  name: ''
});

// 上传表单
const uploadForm = ref({
  name: '',
  personId: undefined,
  personName: '',
  description: '',
  file: null
});

// 上传文件列表
const fileList = ref([]);

// 上传表单验证规则
const uploadRules = reactive({
  name: [{ required: true, message: "请输入资源名称", trigger: "blur" }],
  file: [{ required: true, message: "请选择上传文件", trigger: "change" }]
});

// 获取资源类型名称
function getMediaTypeName(type) {
  const found = mediaTypeOptions.value.find(item => item.value === type);
  return found ? found.label : '未知';
}

// 获取资源类型标签样式
function getMediaTypeTag(type) {
  const typeMap = {
    1: "success",   // 图片
    2: "warning",   // 视频
    3: "info",      // 文档
    4: "primary",   // 音频
    5: ""           // 其他
  };
  return typeMap[type] || "";
}

// 格式化文件大小
function formatFileSize(size) {
  if (!size) return '0 B';
  
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  let i = 0;
  while (size >= 1024 && i < units.length - 1) {
    size /= 1024;
    i++;
  }
  
  return Math.round(size * 100) / 100 + ' ' + units[i];
}

// 查询资源列表
function handleQuery() {
  loading.value = true;
  // 处理日期范围
  const params = { ...queryParams };
  if (dateRange.value && dateRange.value.length === 2) {
    params.beginDate = dateRange.value[0];
    params.endDate = dateRange.value[1];
  }
  
  // 假设这里有一个 API 调用
  // MediaAPI.getList(params)
  //   .then((res) => {
  //     mediaList.value = res.data;
  //     total.value = res.total;
  //   })
  //   .finally(() => {
  //     loading.value = false;
  //   });
  
  // 模拟数据
  setTimeout(() => {
    mediaList.value = [
      {
        id: "1",
        name: "家族合影.jpg",
        type: 1,
        url: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg",
        size: 1024000,
        personId: "1",
        personName: "张三",
        description: "2020年春节家族合影",
        createTime: "2023-01-01 12:00:00"
      },
      {
        id: "2",
        name: "婚礼视频.mp4",
        type: 2,
        url: "https://www.w3schools.com/html/mov_bbb.mp4",
        size: 15360000,
        personId: "2",
        personName: "李四",
        description: "李四婚礼视频",
        createTime: "2023-01-02 12:00:00"
      },
      {
        id: "3",
        name: "家谱文档.docx",
        type: 3,
        url: "#",
        size: 5120000,
        personId: "3",
        personName: "王老先生",
        description: "家谱整理文档",
        createTime: "2023-01-03 12:00:00"
      }
    ];
    total.value = 3;
    loading.value = false;
  }, 500);
}

// 获取人物列表
function getPersonOptions() {
  // PersonAPI.getOptions()
  //   .then((data) => {
  //     personOptions.value = data;
  //   });
  
  // 模拟数据
  personOptions.value = [
    { id: "1", name: "张三" },
    { id: "2", name: "李四" },
    { id: "3", name: "王老先生" },
    { id: "4", name: "赵六" }
  ];
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  dateRange.value = [];
  queryParams.pageNum = 1;
  handleQuery();
}

// 处理每页条数变化
function handleSizeChange(size) {
  queryParams.pageSize = size;
  handleQuery();
}

// 处理页码变化
function handleCurrentChange(page) {
  queryParams.pageNum = page;
  handleQuery();
}

// 媒体点击事件
function handleMediaClick(media) {
  // 可以实现点击媒体项的操作，比如预览
  handlePreview(media);
}

// 打开上传对话框
function handleOpenUploadDialog() {
  getPersonOptions();
  uploadDialog.visible = true;
}

// 关闭上传对话框
function handleCloseUploadDialog() {
  uploadDialog.visible = false;
  uploadFormRef.value.resetFields();
  fileList.value = [];
}

// 处理文件变更
function handleFileChange(file) {
  if (file && file.raw) {
    uploadForm.value.file = file.raw;
    // 如果没有填写名称，使用文件名
    if (!uploadForm.value.name) {
      uploadForm.value.name = file.name;
    }
  }
}

// 处理文件超出限制
function handleExceed() {
  ElMessage.warning('最多只能上传1个文件');
}

// 人物选择变化
function handlePersonChange(personId) {
  const selected = personOptions.value.find(item => item.id === personId);
  if (selected) {
    uploadForm.value.personName = selected.name;
  }
}

// 提交上传
function handleUploadSubmit() {
  uploadFormRef.value.validate((isValid) => {
    if (isValid) {
      if (!uploadForm.value.file) {
        ElMessage.error('请选择要上传的文件');
        return;
      }
      
      // 创建FormData对象
      const formData = new FormData();
      formData.append('file', uploadForm.value.file);
      formData.append('name', uploadForm.value.name);
      formData.append('personId', uploadForm.value.personId || '');
      formData.append('personName', uploadForm.value.personName || '');
      formData.append('description', uploadForm.value.description || '');
      
      // MediaAPI.upload(formData).then(() => {
      //   ElMessage.success('上传成功');
      //   handleCloseUploadDialog();
      //   handleQuery();
      // });
      
      // 模拟上传
      ElMessage.success('上传成功');
      handleCloseUploadDialog();
      handleQuery();
    }
  });
}

// 预览资源
function handlePreview(media) {
  previewDialog.title = media.name;
  previewDialog.url = media.url;
  previewDialog.type = media.type;
  previewDialog.name = media.name;
  previewDialog.visible = true;
}

// 下载资源
function handleDownload(media) {
  // MediaAPI.download(media.id).then((res) => {
  //   // 处理下载
  // });
  
  // 模拟下载
  if (media.url && media.url !== '#') {
    const a = document.createElement('a');
    a.href = media.url;
    a.download = media.name;
    a.click();
  } else {
    ElMessage.info('该文件暂不支持直接下载');
  }
}

// 删除资源
function handleDelete(id) {
  if (!id) {
    ElMessage.warning("请选择要删除的资源");
    return;
  }

  ElMessageBox.confirm("确认删除该资源吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      // MediaAPI.deleteById(id)
      //   .then(() => {
      //     ElMessage.success("删除成功");
      //     handleQuery();
      //   })
      //   .finally(() => {
      //     loading.value = false;
      //   });
      
      // 模拟删除
      setTimeout(() => {
        ElMessage.success("删除成功");
        handleQuery();
        loading.value = false;
      }, 500);
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
.pagination-container {
  margin-top: 15px;
}

.media-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.media-grid {
  margin-top: 15px;
}

.media-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 16px;
}

.media-item {
  cursor: pointer;
  transition: all 0.3s;
  height: 100%;
}

.media-item:hover {
  transform: translateY(-5px);
}

.media-preview {
  height: 160px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background-color: #f5f7fa;
}

.media-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.media-file-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.media-info {
  padding: 12px;
}

.media-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.media-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 12px;
  color: #909399;
}

.media-actions {
  display: flex;
  justify-content: space-between;
}

.preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.preview-image, .preview-video {
  max-width: 100%;
  max-height: 500px;
}

.preview-file {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
  padding: 24px;
}

.preview-file-name {
  font-size: 16px;
  margin-top: 8px;
}
</style>
